(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.wfBpmPkg.uploadController', uploadController);
	uploadController.$inject = [ '$scope', '$q', 'Constants', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService',
			'wfBpmPkgService' ];
	function uploadController($scope, $q, Constants, gridService, modalService, layoutConfig, validatorConfig, authService, wfBpmPkgService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("wfBpmPkgList");
		var wfBpmPkgInfo = $scope.$stateParams.params;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.wfBpmPkg = {};
		
		ctrl.init = function() {
			authService.uploadInit(wfBpmPkgInfo).then(function(response) {
				ctrl.wfBpmPkg = response.data || wfBpmPkgInfo;
				ctrl.wfBpmPkg.bpmPkgName = ctrl.wfBpmPkg.bpmPkgName;
			});
		};

		ctrl.upload = function() {
			if (ctrl.wfBpmPkg.bpmPkgName == null) {
				modalService.openErrorDialogs({
					'messages' : [ 'js.bpm.error.file-required']
				});
			} else {
				ctrl.wfBpmPkg.bpmPkgName = ctrl.wfBpmPkg.bpmPkgName;
				if ( ctrl.wfBpmPkg.bpmPkgName[0]) {
					var fileName = ctrl.wfBpmPkg.bpmPkgName[0].docFileName;
					ctrl.wfBpmPkg.docId = ctrl.wfBpmPkg.bpmPkgName[0].docId;
					
					if ( fileName == null) {
						modalService.openErrorDialogs({
							'messages' : [ 'js.bpm.error.file-required']
						});
					} else {		
						var position = fileName.lastIndexOf(".");
						var fmt = fileName.substring(position + 1, fileName.length);
						if (fmt.toLowerCase() != "jar") {
							modalService.openErrorDialogs({
								'messages' : [ 'js.bpm.error.file-must']
							});         
						} else {		
							//for unique check
							ctrl.wfBpmPkg.serviceCode = fileName.substring(0,3).toUpperCase();
							ctrl.wfBpmPkg.bpmpkgName = fileName;
							return authService.upload(ctrl.wfBpmPkg).then(uploadSuccessful, uploadFailed);
						}
					}
				} else {
					modalService.openErrorDialogs({
						'messages' : [ 'js.bpmpkg.error.file-required']
					});
				} 
			}
		};

		function uploadSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'Upload successfully!' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.wfBpmPkg.upload');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.wfbpmpkg.list',
					'state' : 'cda.wfBpmPkg.list',
					'params' : {}
				}]
			});
		}

		function uploadFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		
	}
})(angular);
